package net.sxnic.workflow.whimpl;

import net.sxnic.workflow.conf.WfConfigUtils;
import net.sxnic.workflow.context.WfContextImpl;
import net.sxnic.workflow.handler.AbstractHandler;
import net.sxnic.workflow.handler.HandlerExt;
import net.sxnic.workflow.handler.WfHandlerException;
import net.sxnic.workflow.node.NodeConfig;
import net.sxnic.workflow.task.Task;
import net.sxnic.workflow.task.util.TaskUtils;
import net.sxnic.workflow.wfentity.WfEntity;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NextAssigneeHandler extends AbstractHandler<WfEntity> implements HandlerExt<WfEntity> {

	private static Logger logger = LoggerFactory.getLogger(NextAssigneeHandler.class);

	public NextAssigneeHandler(WfContextImpl<WfEntity> context) {
		super(context);
	}

	@Override
	public void editExecute() throws WfHandlerException {

		opt();

		logger.debug("==invoker===edit===success==nextAssignees==" + context.getNextAssignees());
		logger.debug("==invoker===edit===success==nextAssigneeHtml===" + context.getNextAssigneesHtml());

	}

	@Override
	public void saveExecute() throws WfHandlerException {
		context.setSelectedNextAssignees(TaskUtils.formatNextAssignees(StringUtils.split(context.getNextAssignee(),
				TaskUtils.NEXTASSIGNEES_SEPARATOR)));
		logger.debug("==invoker===save===success==nextAssignees==" + context.getSelectedNextAssignees());
	}

	@Override
	public void viewExecute() throws WfHandlerException {
		//opt();

	}

	@Override
	public void submitExecute() throws WfHandlerException {
		context.setSelectedNextAssignees(TaskUtils.formatNextAssignees(StringUtils.split(context.getNextAssignee(),
				TaskUtils.NEXTASSIGNEES_SEPARATOR)));
		logger.debug(context.getNextAssignee() + "==invoker===submit===success==nextAssignees=="
				+ context.getSelectedNextAssignees());
	}

	private void opt() throws WfHandlerException {
		
		//如果是最后一个节点则不需要创建接收人
		if("end".equals(context.getTask().getNode().getCate())){
			return;
		}		
		
		// 可选接收人列表
		String nextAssignees = "";
		try {
			nextAssignees = WfConfigUtils.getNextAssigneeByProcessNode(context.getProcessName(), context.getTaskName());
			
			if(nextAssignees.contains(NodeConfig.DEFAULTASSIGNEE_DRAFTER)){
				Task startTask =context.getTaskManager().findFirstTask(context.getEntityId());
				if(startTask!=null){
					nextAssignees = StringUtils.replace(nextAssignees, NodeConfig.DEFAULTASSIGNEE_DRAFTER, startTask.getAssignee());
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new WfHandlerException(e.toString());
		}
		
		context.setNextAssigneesHtml(TaskUtils.createReceiversHtml(nextAssignees));
	}

}
